package com.mongo.plus.demo.config;

import com.anwen.mongo.transactional.MongoPlusTransactionalManager;
import com.mongodb.TransactionOptions;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @ClassName MongoPlusConfig
 * @Description:
 * @CreateDate: 2024/12/28 11:55
 * @Version: 1.0
 */
@Configuration
public class MongoPlusConfig {

    /**
     * mongodb 乐观锁配置
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor mongoOptimisticLockerInterceptor() {
        OptimisticLockerInterceptor optimisticLockerInterceptor = new OptimisticLockerInterceptor();
        // 修改失败后是否抛出异常抛出异常
        optimisticLockerInterceptor.setUpdateFailException(new OptimisticLockingFailureException("Mongo Optimistic Locker Exception!"));
        // 设置乐观锁自增值
        optimisticLockerInterceptor.setAutoInc(1);
        // 是否开启重试
        return optimisticLockerInterceptor;
    }


    public static final String MONGO_TR_MANAGER = "mongoTransactionManager";
    public static final String MONGO_TR_TEMPLATE = "mongoTransactionTemplate";


    /**
     * 可选 mongo 事务，该事务不可嵌套
     *
     * @param options
     * @return
     */
    @Bean(name = MONGO_TR_MANAGER)
    public MongoPlusTransactionalManager mongoTransactionManager(TransactionOptions options) {
        return new MongoPlusTransactionalManager(options);
    }


    /**
     * mongo事务模板
     *
     * @param transactionManager
     * @return
     */
    @Bean(name = MONGO_TR_TEMPLATE)
    public TransactionTemplate mongoTransactionTemplate(@Qualifier(MONGO_TR_MANAGER) MongoPlusTransactionalManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }
}
